最近小弟有個使用資料表的需求,之前使用過material ui,就整體畫面來說是個不錯的套件,可惜在資料呈現上相對普通。剛好最近看到商用軟體progress的ui模塊,他對於資料的呈現有相對較多的資源,可以繪製各式圖表,這邊簡單做個整理與分享。
使用 create-react-app 快速建立 npm project
npx create-react-app my-kendo
cd my-kendo
安裝npm依賴
npm install --save @progress/kendo-react-grid @progress/kendo-data-query @progress/kendo-react-inputs @progress/kendo-react-intl @progress/kendo-react-dropdowns @progress/kendo-react-dateinputs
首先更改./public/index.html
內容,引入css
<head>
<link rel="stylesheet" href="https://unpkg.com/@progress/kendo-theme-material@latest/dist/all.css"></link>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div id="root"></div>
</body>
建立資料./src/products.json
[{
"ProductID" : 1,
"ProductName" : "Chai",
"UnitsInStock" : 39,
"Discontinued" : false,
"Category" : {
"CategoryID" : 1,
"CategoryName" : "Beverages"
}
},{
"ProductID" : 2,
"ProductName" : "Chang",
"UnitsInStock" : 21,
"Discontinued" : true,
"Category" : {
"CategoryID" : 2,
"CategoryName" : "Produce"
}
}]
新增檔案./src/dataTable.js
並寫入以下內容
import React from 'react';
import { Grid, GridColumn as Column } from '@progress/kendo-react-grid';
// 產品目錄(資料)
import products from './products.json';
class DataTable extends React.Component {
constructor(props) {
//在子类的constructor中必须先调用super才能引用this
super(props);
// 初始化狀態
this.state = {
gridData:products
};
}
render(){
return(
<Grid
style={{ height: '400px',width:'650px' }}
data={this.state.gridData}
>
<Column field='ProductID' title='ID' width='50px' />
<Column field='ProductName' title='Product Name' width='160px' />
<Column field='UnitsInStock' title='Units In Stock' width='160px'/>
<Column field='Discontinued' width='120px'
cell={(props) => {return (
<td>
<input disabled type='checkbox' checked={props.dataItem[props.field]} />
</td>
);}}
/>
<Column field='Category.CategoryName' title='CategoryName' width='150px' />
</Grid>
);
}
}
export default DataTable;
修改./src/App.js
內容
import React from 'react';
import DataTable from './dataTable.js';
function App() {
return (
<div>
<DataTable />
</div>
);
}
export default App;
最後只要執行npm start
就可以看到我們的資料表了!
順帶附上github給大家參考
我們在kendo ui裡面只要注意Grid的data屬性與Column的field屬性,即可快速呈現表格。